package com.jn.algorithm.day019.question56;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @author 江南大学1033190417
 * @date 2022/5/10 21:00
 */
public class Solution {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });
        List<int[]> res = new ArrayList<>();
        int[] temp = new int[]{intervals[0][0], intervals[0][1]};
        for (int i = 1; i < intervals.length; i++) {
            int[] now = intervals[i];
            //如果当前的区间和temp有交集
            if (now[0] <= temp[1]) {
                temp[1] = Math.max(temp[1], now[1]);
            } else {
                res.add(Arrays.copyOf(temp, 2));
                temp = intervals[i];
            }
        }
        res.add(temp);
        return res.toArray(new int[res.size()][]);
    }

    public static void main(String[] args) {
        int[][] intervals = new int[][]{
                {1, 3},
                {2, 6},
                {8, 10},
                {15, 18}
        };
        Solution solution = new Solution();
        int[][] merge = solution.merge(intervals);
        for (int[] t : merge) {
            System.out.println(Arrays.toString(t));
        }
    }
}
